package conn

import (
	"net"
	"strconv"
	"strings"
)

type Addr interface {
	Type() string    // name of the network (for example, "tcp", "udp")
	Network() string // name of the network (for example, "tcp", "udp")
	Addr() string    //string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
	IP() string      //split of addr ,find ip
	Port() int       //split of addr ,find port
	String() string  // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
}

type addr struct {
	addr net.Addr
	ip   string
	port int
}

func NewAddr(a net.Addr) Addr {
	data := addr{addr: a}
	if a != nil {
		list := strings.Split(a.String(), ":")
		if len(list) == 2 {
			data.ip = list[0]
			data.port, _ = strconv.Atoi(list[1])
		}
	}
	return data
}

// Type "tcp","udp"
func (a addr) Type() string {
	return a.addr.Network()
}

// Network "tcp","udp"
func (a addr) Network() string {
	return a.addr.Network()
}

// Addr "192.0.2.1:25", "[2001:db8::1]:80"
func (a addr) Addr() string {
	return a.addr.String()
}

// IP 127.0.0.1
func (a addr) IP() string {
	return a.ip
}

// Port 端口 8000
func (a addr) Port() int {
	return a.port
}

// String "192.0.2.1:25", "[2001:db8::1]:80"
func (a addr) String() string {
	return a.addr.String()
}
